import { login } from '../api/api';
const app = getApp();

export function px2rpx(pxNum) {
    if (!app.globalData || !app.globalData.windowWidth) {
        throw Error('获取不到屏幕宽度')
    }
    return pxNum * 750 / app.globalData.windowWidth;
}

export function rpx2px(rpxNum) {
    if (!app.globalData || !app.globalData.windowWidth) {
        throw Error('获取不到屏幕宽度')
    }
    return rpxNum * app.globalData.windowWidth / 750;
}

/**
 * 日期格式化 yyyy-mm-dd hh:mm:ss
 * @param {*} date Date
 */
export function dateFormat(date) {
    return date.toJSON().substr(0, 19).replace('T', ' ');;
}

/**
 * 拼接 url
 * @param {string} url
 * @param {object} params
 */
export function getUrl(url, params) {
    let paramsStr = '';
    for (var key in params) {
        paramsStr += `${paramsStr ? '&' : ''}${key}=${params[key]}`
    }
    return `${url}${paramsStr ? '?' + paramsStr : ''}`;
}


/**
 * 弹窗
 * @param {string} title 提示标题
 * @param {string} content 提示内容
 * @param {function} callback 回调函数
 */
export function showDialog({
    title,
    content,
    showCancel,
    confirmText,
    successCb,
    cancelCb
}) {
    wx.showModal({
        title,
        content,
        showCancel: showCancel || false, // 是否展示取消按钮, 默认不展示
        confirmText: confirmText || '我知道啦',
        success({ confirm, cancel }) {
            if (confirm) {
                successCb && successCb()
            }
            if (cancel) {
                cancelCb && cancelCb()
            }
        },
    })
}

/**
 * 跳转到主页
 */
export function linkToHome() {
    wx.navigateTo({
        url: `../home/home`,
    })
}

/**
 * 跳转到绘画页
 */
export function linkToDraw(drawBoardId) {
    wx.navigateTo({
        url: `../draw/draw?id=${drawBoardId}`,
    })
}

/**
 * 刷新当前页面
 */
export function refresh() {
    const { route, options } = getCurrentPages()[0]
    const curUrl = getUrl(route, options);
    wx.redirectTo({
        url: '/' + curUrl
    })
}

/**
 * 检查登录状态
 * @returns promise 成功返回 userInfo 
 */
export function getUserInfo(isFromBtn = true) {
    return new Promise(async (resolve, reject) => {
        // 从缓存获取用户信息
        let userInfo = wx.getStorageSync('userInfo');

        // 登录过
        if (userInfo) {
            resolve(userInfo);
            return;
        }

        // 未登录
        // 通过按钮调用, 可以直接调用 wx.getUserProfile
        if (isFromBtn) {
            getUserInfoAndLogin().then(res => resolve(res))
        } else { // 否则需要通过弹窗来调用
            showDialog({
                title: '未登录',
                content: '登录后才可以和朋友一起涂鸦哦～',
                confirmText: '登录',
                successCb: () => {
                    getUserInfoAndLogin()
                        .then(res => resolve(res))
                        .catch(() => reject());
                },
                cancelCb: () => reject(),
            })
        }

    })
}

export function getUserInfoAndLogin(params) {
    return new Promise((resolve, reject) => {
        wx.getUserProfile({
            desc: '登录后和好友一起涂鸦吧',
            success: async (res) => {
                const userInfo = res.userInfo;
                wx.setStorageSync('userInfo', userInfo);
                await login(userInfo);
                resolve(userInfo);
            },
            fail: () => {
                wx.showToast({
                    title: '登录授权失败',
                    icon: 'error',
                    duration: 2000
                })
                reject()
            }
        })
    })

}

/**
 * 防抖
 */
export function debounce(fn, wait) {
    let _timer;
    return function () {
        const that = this;
        const args = arguments;
        if (_timer) {
            clearTimeout(_timer);
            _timer = null;
        }

        _timer = setTimeout(() => {
            fn.call(that, args);
        }, wait);
    };
}

/**
 * 节流(立即执行)
 */
export function throttle(fn, delay = 0) {
    let _timer;
    return function () {
        const that = this;
        const args = arguments;
        if (!_timer) {
            fn.call(that, args);
            _timer = setTimeout(() => {
                _timer = null;
            }, delay);
        }
    };
}